package com.slf.engine.threads;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

import com.slf.engine.common.SysContext;
import com.slf.engine.exception.EngineException;
import com.slf.engine.http.HttpClientManager;
import com.slf.engine.http.HttpResponseWrapper;
import com.slf.engine.services.IFcjs0573Service;
import com.slf.engine.services.impl.Fcjs0573ServiceImpl;

public class HeartThread extends Thread {

	private static final Logger log = Logger.getLogger(HeartThread.class);
	private HttpClientManager manager;
	private String url;
	private String charset;
	private String content;
	public HeartThread(HttpClientManager manager, String url,String charset,String content)
	{
		log.log(Priority.INFO, "心跳链接启动");
		this.manager = manager;
		this.url = url;
		this.charset = charset;
		this.content = content;
	}
	
	public void run()
	{
		IFcjs0573Service service = new Fcjs0573ServiceImpl();
		while(true)
		{
			if(SysContext.IS_START)
			{
				if(SysContext.FREE_TIME == 0 || System.currentTimeMillis() - SysContext.FREE_TIME > 1000 * 30)
				{
					if(!doHeart())
					{
						if(service.login(manager))
						{
							log.log(Priority.INFO, "心跳重新登录成功");
							SysContext.FREE_TIME = System.currentTimeMillis();
						}else{
							SysContext.IS_START = false;
							log.log(Priority.INFO, "心跳重新登录失败");
						}
					}else{
						SysContext.IS_START = false;
						log.log(Priority.INFO, "心跳访问失败");
					}
				}else{
					try {
						this.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
					}
				}
			}else{
				try {
					log.log(Priority.INFO, "心跳链接重试");
					this.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
			}
		}
	}
	
	private boolean doHeart()
	{
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", url, charset, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return doHeart();
			}
			String body = new String(wrapper.getBody());
			if(body.indexOf(content) != -1)
			{
				return true;
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			return doHeart();
			
		}
		return false;
	}
	
}
